<?php

namespace app\controller\bossManager;

use app\exception\ErrnoPlus;
use app\validate\SimBindDeviceValidate;
use app\validate\PageValidate;
use share\service\SimBindDeviceService;
use share\service\Factory4gManagerTableService;

class SimBindDeviceController extends WebBossController
{
    public function initValidate()
    {
        $this->validate = new SimBindDeviceValidate();
    }

    public function list_action()
    {
        $param = $this->request->param();
        $page = $this->check('pageInfo', null, (new PageValidate()));
        $data = SimBindDeviceService::getListInfo($param, $page);
        $total = SimBindDeviceService::getListCountInfo($param);
        return self::ok(self::formatPageData($page, $total, $data));
    }

    public function set_action()
    {
        $input = $this->check();
        $res = SimBindDeviceService::edit($input);
        return self::ok($res);
    }

    public function del_action()
    {
        $input = $this->check();
        $res = SimBindDeviceService::del($input['id']);
        return self::ok($res);
    }

    public function bulk_update_action(){
        $importData = $this->request->param('data');
        if(empty($importData) || !is_array($importData)){
            return self::fail("导入数据格式不正确",ErrnoPlus::COMMON_INVALID_INPUT);
        }

        if(count($importData) > 100){
            return self::fail("too many datas",ErrnoPlus::COMMON_INVALID_INPUT);
        }
        $usefulData = [];
        $errorData = [];
        $this->validate->scene('importUpdateData');
        $rule = $this->validate->getSceneRule();
        $this->validate->rule($rule);
        foreach($importData as $data){
            if($this->validate->check($data)){
                $usefulData[] = $data;
            }
            else{
                $data['error'] = $this->validate->getError();
                $errorData[] = $data;
            }
        }
        $res = SimBindDeviceService::bulkUpdate($usefulData);
        $res['errorData'] = array_merge($errorData,$res['errorData']);
        return self::ok($res);
    }

    /**
     * 卡商列表
     */
    public function factory_list_action()
    {
        $data = Factory4gManagerTableService::getAllByFilter([]);
        $res = [];     
        foreach($data as $key => $d){
            $res[] = [
                'key' => $key,
                'factoryId' => $d['factoryId'],
                'factoryName' => $d['factoryName'],
            ];
        }
        return self::ok($res);
    }
}
